package cn.kgm.controller;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

@Slf4j
public class HelloWorldPubSubController {
    public static void main(String[] args) throws Exception {
        log.info("rabitmq-sending..." );
        // 1.创建链接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 2.设置参数
        factory.setHost("localhost" );
        factory.setPort(5672);
        factory.setUsername("kagim" );
        factory.setPassword("kagim" );
        factory.setVirtualHost("/virtual-kagim" );
        // 3.创建链接
        Connection connection = factory.newConnection();
        // 4.创建通道（chanal）
        Channel channel = connection.createChannel();
        // 5.创建交换机
        String exchangeName = "test_fanout";
        // fanout = 广播模式，交换机会给所有绑定他的队列发送消息（消息份数=发的条数X队列个数）
        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.FANOUT, true, false, null);
        // 6.创建队列
        String queue1 = "test_fanout_queue1";
        String queue2 = "test_fanout_queue2";
        channel.queueDeclare(queue1, true, false, false, null);
        channel.queueDeclare(queue2, true, false, false, null);
        // 7.绑定队列和交换机
//        String queue, String exchange, String routingKey, Map<String, Object> arguments
        channel.queueBind(queue1, exchangeName, "", null);
        channel.queueBind(queue2, exchangeName, "", null);
        // 8.发送消息
        String body = "今天建哥将日志发送到mq了！";
        // 订阅发布者模式时，roteingkey 不设置，默认将信息发送给所有绑定了交换机的队列
        channel.basicPublish(exchangeName, "", null, body.getBytes(StandardCharsets.UTF_8));
        channel.close();
        connection.close();
    }
}
